package net.kid06.mybatis.user;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

public class UserFirst {

	@Test
	public void insertUser() throws Exception {
		SqlSession sqlSession = getSqlSession();
		Map<String, Object> map = new HashMap<>();
		map.put("username", "dengdai");
		map.put("password", "123456");
		map.put("nickname", "等待");
		map.put("phone", "13067752280");
		map.put("age", 10);
		map.put("tab_vip_id", 1);
		map.put("gender", 1);
		map.put("type", 1);
		sqlSession.insert("mybatis.insertUser", map);

		sqlSession.commit();

		sqlSession.close();
	}

	@Test
	public void deleteUserByName() throws Exception {
		SqlSession sqlSession = getSqlSession();
		sqlSession.delete("mybatis.deleteUserByName", "admin3");
		sqlSession.commit();
		sqlSession.close();
	}

	@Test
	public void findAll() throws Exception {
		SqlSession sqlSession = getSqlSession();
		List<UserEntity> list = sqlSession.selectList("mybatis.findAll");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i).toString());
		}
		sqlSession.close();
	}

	@Test
	public void selectUser() {
		try {
			SqlSession sqlSession = getSqlSession();
			//
			Map<String, Object> map = new HashMap<>();
			map.put("id", 1);
			map.put("username", "admin");
			UserEntity userEntity = sqlSession.selectOne("mybatis.selectUser", map);
			//
			System.out.println(userEntity.toString());
			//
			sqlSession.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void findByName() throws Exception {
		SqlSession sqlSession = getSqlSession();
		List<UserEntity> list = sqlSession.selectList("mybatis.findByName", "admin");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i).toString());
		}
		sqlSession.close();
	}

	/**
	 * 读取配置文件 获取SqlSession
	 * 
	 * @return
	 * @throws Exception
	 */
	public SqlSession getSqlSession() throws Exception {
		String resource = "mybatis_config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		return sqlSessionFactory.openSession();
	}
}
